/****************************
 * 权限验证
 ****************************/

(function () {

    exports.Vpermissions = function(req,res,next){

        
        if(!config.permissionConfig.isUserPermission){
            return next()
        }

        //判断如果为GET请求，或者为需要筛选字段的POST请求，不进行权限验证操作
        if(req.method == 'GET' || req.body.fields != undefined){
            return next()
        }

        //不是超管，进行相关操作权限验证，取出本次访问的接口是转发请求，还是中间层拦截请求
		var firstMenuLevelName = req.params.firstMenuLevel;

		//获取二级菜单名称
		var secondMenuLevelName = req.params.secondMenuLevel;

		//拼接完整接口地址
        var resultApiName = '/' + firstMenuLevelName + '/' + secondMenuLevelName;

        //获取接口权限声明信息
        var interfaceInfo = APIConfig.API[resultApiName];

        //判断是否为白名单中的接口，如果是，则不进行权限验证
        if( config.permissionConfig.permissionWhiteList.indexOf(resultApiName) != -1 ){
            return next()
        }
  
        //是否为超管
        var isAdmin   = req.headers["is-admin"];

        //当前菜单的操作权限组
        var actionIds = req.headers["action-ids"];

        //检查权限参数是否存在
        if(isAdmin == undefined || actionIds == undefined){
            return RES.errorResponse(res,'抱歉，缺少权限验证参数，请检查');
        }

        //判断是否为超管，如果为超管，直接跳过权限验证
        if(isAdmin == 'true'){
            return next()
        }

        //判断是否开启操作级权限验证
        if( !config.permissionConfig.isOpenActionPermission ){
            return next()
        }

        var inStr = "";

        //判断请求是转发还是拦截，组建相应的权限查询语句
        if (interfaceInfo == undefined) {

            //获取核心层接口操作Ids
            inStr = resultApiName.replace(/\//g,"@")

        }else{

            //判断是否有权限声明
            var permissionData = interfaceInfo.permissions;

            //不需要任何权限可访问，直接跳过
            if(permissionData == undefined || permissionData.length <= 0){
               return next()
            }

            //拼接In条件语句
            inStr = permissionData.join(",");

            inStr = inStr.replace(/\//g,"@")

        }

    
        //请求所需权限
        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.actionPermissionsSearch.Request_Api_Url + "/in/ap_api-" + inStr + "/skip/0/limit/1000",
                method : 'POST',
                data : {
                    fields : "ap_id,ap_name"
                }
            },
            function (data) {

                //所声明权限接口的Ids
                var actionPermissionsData = data.result.data;

                if(actionPermissionsData.length <= 0){
                    return next()
                }

                var permissionArr = [];

                //将权限结果转化为纯数组
                for(var i = 0;i<actionPermissionsData.length;i++){
                    permissionArr.push(actionPermissionsData[i].ap_id);
                }

                //用户所拥有的操作
                var actionIdsArr = actionIds.split(",")

                //查询权限交集
                var permissionValue = common.intersect(actionIdsArr,permissionArr);

                //查询权限差集
                var minusPermissionValue = common.minus(permissionArr,actionIdsArr);

                //根据差集拿到没有的权限操作名
                var noPermissionNames = "";
                for(var i =0;i<actionPermissionsData.length;i++){
                    for(var k=0;k<minusPermissionValue.length;k++){
                        if(actionPermissionsData[i].ap_id == minusPermissionValue[k]){
                            noPermissionNames += actionPermissionsData[i].ap_name + ",";
                        }
                    }
                }

                noPermissionNames = common.takeStrLast(noPermissionNames)

                if( JSON.stringify(permissionValue.sort()) != JSON.stringify(permissionArr.sort()) ) {
                    return RES.errorResponse(res,'抱歉，该用户无权进行相关操作，缺少以下操作权限：[ ' + noPermissionNames + " ] ，请检查。");
                }

                //通过权限验证
                next()

            }
        )
    }   


}).call(this);